package com.shayu.aicodemother.controller;

import com.mybatisflex.core.paginate.Page;

import com.shayu.aicodemother.annotation.AuthCheck;
import com.shayu.aicodemother.common.BaseResponse;
import com.shayu.aicodemother.common.DeleteRequest;
import com.shayu.aicodemother.common.ResultUtils;
import com.shayu.aicodemother.constant.UserConstant;
import com.shayu.aicodemother.exception.BusinessException;
import com.shayu.aicodemother.exception.ErrorCode;
import com.shayu.aicodemother.exception.ThrowUtils;
import com.shayu.aicodemother.model.dto.user.*;
import com.shayu.aicodemother.model.entity.User;
import com.shayu.aicodemother.model.vo.LoginUserVO;
import com.shayu.aicodemother.model.vo.UserVO;
import com.shayu.aicodemother.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户 控制层。
 *
 * @author <a href="https://so.gitee.com/?q=%E8%8E%8E%E5%A3%AB%E6%AF%94%E8%B0%AD">程序员鲨鱼</a>
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 注册
     *
     * @param userRegisterDto
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterDto userRegisterDto) {
        //有错误直接抛出
        ThrowUtils.throwIf(userRegisterDto == null, ErrorCode.PARAMS_ERROR);

        Long userId = userService.UserRegister(userRegisterDto.getUserAccount(), userRegisterDto.getUserPassword(), userRegisterDto.getCheckPassword());

        return ResultUtils.success(userId);

    }

    /**
     * 登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userService.userLogin(userLoginRequest, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 通过Session登录
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLoginout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(userService.userLoginout(request));
    }

    /**
     * 创建用户。
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        //默认密码为12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryPassword = userService.getEncryPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryPassword);
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());

    }

    /**
     * 根据主键删除用户。
     */
    @DeleteMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> remove(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);


    }

    /**
     * 根据主键更新用户。
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> update(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean b = userService.updateById(user);
        ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);
        return ResultUtils.success(b);
    }

    /**
     * 根据用户id获取用户----管理员才能使用
     *
     * @param id 用户主键
     * @return 用户详情
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getInfo(@RequestParam Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }


    /**
     * 根据id查找用户，查找到包装后的消息
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVo(Long id) {
        BaseResponse<User> info = getInfo(id);
        User user = info.getData();
        return ResultUtils.success(userService.getUserVo(user));
    }


    /**
     * 管理员分页获取用户管理列表
     *
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {

        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int pageNum = userQueryRequest.getPageNum();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> page = userService.page(Page.of(pageNum, pageSize), userService.getQueryRequest(userQueryRequest));
        //数据脱敏
        Page<UserVO> PageVo = new Page<>(pageNum, pageSize, page.getTotalRow());
        List<UserVO> userVolist = userService.getUserVoList(page.getRecords());
        PageVo.setRecords(userVolist);
        return ResultUtils.success(PageVo);
    }
}
